using DailyPoetryH.Library.Models;
using Microsoft.AspNetCore.Components;

namespace DailyPoetryH.Library.Pages;

public partial class Detail {
    [Parameter] public string PoetryId { get; set; } = string.Empty;

    private Poetry _poetry = new();

    private bool _isLoadingPoetry = true;

    private bool _isLoadingFavorite = true;

    private Models.Favorite _favorite = new();

    protected override async Task OnAfterRenderAsync(bool firstRender) {
        if (!firstRender) {
            return;
        }

        if (string.IsNullOrWhiteSpace(PoetryId)) {
            return;
        }

        if (!int.TryParse(PoetryId, out var poetryId)) {
            return;
        }

        _isLoadingPoetry = true;
        _isLoadingFavorite = true;
        StateHasChanged();

        _poetry = await _poetryStorage.GetPoetryAsync(poetryId) ??
            new Poetry { Id = poetryId };
        _isLoadingPoetry = false;
        StateHasChanged();

        _favorite = await _favoriteStorage.GetFavoriteAsync(_poetry.Id) ??
            new Models.Favorite { PoetryId = _poetry.Id };
        _isLoadingFavorite = false;
        StateHasChanged();
    }

    private async Task ValueChanged() {
        _isLoadingFavorite = true;
        StateHasChanged();

        await _favoriteStorage.SaveFavoriteAsync(_favorite);

        _isLoadingFavorite = false;
        StateHasChanged();
    }
}